<template>
  <page-header-wrapper>
    <applicationSearch
      :filterFields="[
        'BeviewResult',
        'CityVfyAgent',
        'ApplyClass',
        'CityVfyAssign',
        'SubmitToCity',
        'ProcessDate',
        'ProcessUser',
        'CityVfyDate',
        'VerifyResult',
        'CityVfyResult',
        'CityRfyDate',
        'CityRfyResult',
      ]"
      @search="handleSearch"
      @reset="handleReset"
    ></applicationSearch>
    <a-card :bordered="false">
      <s-table
        ref="table"
        size="default"
        rowKey="ID"
        :columns="columns"
        :data="loadData"
        :pagination="{ showTotal: (total) => `共 ${total} 条` }"
      >
        <span slot="index" slot-scope="text, record, index">{{ index + 1 }} </span>
        <div slot="action" slot-scope="text, record">
          <y-button type="link" @click="handleDetail(record.ID)">查看</y-button>
          <y-button
            type="link"
            v-if="$isEmpty(record.Esites) || record.Esites === '0'"
            @click="handleDistribution(record)"
            >分配</y-button
          >
          <a-popconfirm
            v-else
            title="确认取消分配此房源？"
            placement="left"
            @confirm="handleDistributionCancel(record)"
          >
            <y-button type="link" class="text-error">取消分配</y-button>
          </a-popconfirm>
        </div>
      </s-table>
    </a-card>
    <house-list
      ref="houseList"
      :visible.sync="visibleHouseList"
      :searchList.sync="houseSearchList"
      :loadData="loadHouseList"
      :houseParams="houseParams"
      :actions="houseActions"
      title="自行备案实物分配"
      @HoueTypeColor="handelHoueTypeColor"
    >
      <div slot="action" slot-scope="scope">
        {{ scope.house.ID }}
      </div>
    </house-list>
    <house-detail :visible.sync="visibleDetail" :houseID="houseItem.ID"></house-detail>
  </page-header-wrapper>
</template>

<script>
import { STable, Ellipsis, houseList, applicationSearch, houseDetail } from '@/components'
import { postHouseDistribution } from '@/api/recordByOneself'
import {
  getProposerList,
  getHousingEstateList,
  getHouseIdRoof,
  getHouseRoofidTotalFloor,
  getHouseList,
} from '@/api/common'

export default {
  components: {
    STable,
    Ellipsis,
    houseList,
    applicationSearch,
    houseDetail,
  },
  data() {
    return {
      houseTypeOptions: [],
      queryParam: {
        UserID: this.$store.getters.userid,
        Mode: 'EnterpriseFiling',
        strContent: {},
      },
      visibleHouseList: false,
      proposer: {},
      visibleDetail: false,
      houseItem: {},
      houseActions: [
        {
          tooltip: '分配',
          icon: 'fl-renyuan',
          show: (e) => {
            return e.Mode === '空置'
          },
          onClick: (e) => {
            this.$confirm({
              title: '提示',
              content: `确定要分配${e.Floor}-${e.Number}该房屋？`,
              onOk: () => {
                return postHouseDistribution({
                  State: 'update',
                  HousesID: e.ID,
                  UserID: this.$store.getters.userid,
                  ProposerID: this.proposer.ID,
                }).then((res) => {
                  this.$message.success('实物分配成功')
                  this.visibleHouseList = false
                  this.proposer = {}
                  this.$refs.table.refresh()
                })
              },
            })
          },
        },
        {
          tooltip: '查看',
          icon: 'eye',
          theme: 'filled',
          onClick: (e) => {
            this.houseItem = e
            this.visibleDetail = true
          },
        },
      ],
      houseParams: [
        {
          label: '房屋编号',
          custom: (house, floor) => {
            return `${floor}-${house.Number}`
          },
        },
        {
          label: '房屋结构',
          key: 'fwjg',
        },
        {
          label: '房屋面积',
          key: 'Area',
        },
        {
          label: '房屋状态',
          key: 'Mode',
        },
        {
          label: '现居住人',
          key: 'Name',
          custom: (house, floor) => {
            return house.Name || '暂无居住人'
          },
        },
      ],
      houseSearchList: [
        {
          label: '小区名称',
          fields: 'housesid',
          type: 'select',
          validate: [{ required: true, message: '请选择小区' }],
          props: {
            placeholder: '请选择小区',
            options: [],
          },
          methods: {
            change: (housesid) => {
              this.$refs.houseList.$searchForm.setFieldsValue({
                housesroofid: undefined,
                lcid: undefined,
                mode: undefined,
              })
              for (let index = 1; index <= 2; index++) {
                this.houseSearchList[index].props.options = []
                this.houseSearchList[index].props.disabled = true
              }
              getHouseIdRoof({ housesid }).then((res) => {
                this.houseSearchList[1].props.options = res.map((e) => {
                  return {
                    value: e.ID,
                    label: `${e.ROOF}栋${e.UNIT}单元`,
                  }
                })
                this.houseSearchList[1].props.disabled = false
              })
            },
          },
        },
        {
          label: '栋号',
          fields: 'housesroofid',
          type: 'select',
          validate: [{ required: true, message: '请选择栋号' }],
          props: {
            placeholder: '请选择栋号',
            options: [],
            disabled: true,
          },
          methods: {
            change: (housesroofid) => {
              this.$refs.houseList.$searchForm.setFieldsValue({
                lcid: undefined,
                mode: undefined,
              })
              this.houseSearchList[2].props.options = []
              this.houseSearchList[2].props.disabled = true
              getHouseRoofidTotalFloor({ housesroofid }).then((res) => {
                this.houseSearchList[2].props.options = res.map((e) => {
                  return {
                    value: e.FLOOR,
                    label: e.FLOOR + '层',
                  }
                })
                this.houseSearchList[2].props.disabled = false
              })
            },
          },
        },
        {
          label: '楼层',
          fields: 'lcid',
          type: 'select',
          props: {
            placeholder: '请选择楼层',
            options: [],
            disabled: true,
          },
        },
        {
          label: '房源状态',
          fields: 'mode',
          type: 'select',
          props: {
            placeholder: '请选择房源状态',
            options: [],
          },
        },
        // {
        //   label: '跳转测试',
        //   fields: 'tzcs',
        //   type: 'select',
        //   props: {
        //     options: [
        //       { value: '3', label: '3' },
        //       { value: '4', label: '4' }
        //     ]
        //   },
        //   methods: {
        //     change: (e) => {
        //       document.getElementById(`floor-${e}`).scrollIntoView(true)
        //     }
        //   }
        // }
      ],
      columns: [
        {
          title: '序号',
          align: 'center',
          width: '80px',
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '申请编号',
          align: 'center',
          dataIndex: 'ApplyNo',
        },
        {
          title: '申请人',
          align: 'center',
          dataIndex: 'Proposer',
        },
        {
          title: '身份证号',
          align: 'center',
          dataIndex: 'IDCard',
        },
        {
          title: '申请类别',
          align: 'center',
          dataIndex: 'ApplyClass',
        },
        {
          title: '所属区级',
          align: 'center',
          dataIndex: 'RegionName',
        },
        {
          title: '所属企业',
          align: 'center',
          dataIndex: 'TownshipName',
        },
        {
          title: '操作',
          align: 'center',
          width: '160px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getProposerList(requestParameters).then((res) => {
          return res
        })
      },
      loadHouseList: (parameter, strContent) => {
        if (this.$isEmpty(strContent)) {
          return Promise.resolve({
            data: [],
            count: 0,
          })
        }
        const { mode, lcid, housesroofid, housesid } = strContent
        return getHouseList({
          ...parameter,
          mode: mode || '',
          lcid: lcid || '',
          housesroofid: housesroofid || '',
          housesid: housesid || '',
        }).then((res) => res)
      },
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      const getHousingEstate = getHousingEstateList({
        State: 'qiye',
        UserID: this.$store.getters.userid,
      })
      Promise.all([getHousingEstate]).then((res) => {
        this.houseSearchList[0].props.options = res[0].map((e) => {
          return {
            value: e.ID,
            label: e.NAME,
          }
        })
      })
    },
    handleSearch(values) {
      this.queryParam.strContent = values
      this.$refs.table.refresh(true)
    },
    handleReset() {
      this.queryParam.strContent = {}
      this.$refs.table.refresh(true)
    },
    handleDetail(id) {
      localStorage.setItem('browserCacheDetail', JSON.stringify({ id: id }))
      this.$router.push({
        name: 'recordByOneSelfDetail',
        params: {
          id,
        },
      })
    },
    handleDistribution(record) {
      this.proposer = record
      this.visibleHouseList = true
    },
    handelHoueTypeColor(options) {
      this.houseTypeOptions = options
      this.houseSearchList[3].props.options = this.houseTypeOptions
    },
    handleDistributionCancel(record) {
      this.$loading.show({
        tip: '取消分配中，请稍后...',
      })
      postHouseDistribution({
        State: 'esc',
        HousesID: record.Esites,
        UserID: this.$store.getters.userid,
        ProposerID: record.ID,
      })
        .then((res) => {
          this.$message.success('取消分配成功！')
          this.$refs.table.refresh()
        })
        .finally(() => {
          this.$loading.hide()
        })
    },
  },
}
</script>
<style lang="less" scoped>
.table-header {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>
